package com.wing.qualityTesting.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.Idempotent;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.productionPlan.model.entity.ProAbnormalCause;
import com.wing.productionPlan.model.entity.QualityTestingRecordDetail;
import com.wing.productionPlan.model.response.QualityTestingRecordDetailVO;
import com.wing.productionPlan.service.QualityTestingRecordDetailService;
import com.wing.qualityTesting.model.entity.QualityTestingRecord;
import com.wing.qualityTesting.model.entity.QualityTestingRecordValue;
import com.wing.qualityTesting.model.request.QualityRecordAddOrUpdateForm;
import com.wing.qualityTesting.model.request.QualityTestingRecordForm;
import com.wing.qualityTesting.model.response.*;
import com.wing.qualityTesting.service.QualityTestingRecordService;
import com.wing.qualityTesting.service.QualityTestingRecordValueService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-质检记录表管理", tags = "#/res/quality/taskQualityRecord")
@RestController("resTaskQualityRecordController")
@RequestMapping("quality/admin/taskQualityRecord")
@RequiredArgsConstructor
public class ResTaskQualityRecordController {

    @Autowired
    private QualityTestingRecordService qualityTestingRecordService;

    @Autowired
    private QualityTestingRecordDetailService qualityTestingRecordDetailService;

    @Autowired
    private QualityTestingRecordValueService qualityTestingRecordValueService;

    @ApiOperation(value = "查询所有质检记录表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "processId", value="工序id", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "code", value="质检记录编号", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "workOrderCode", value="工单编号", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "inspectionPeople", value="送检人", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "creatorName", value="检验员", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<QualityTestingRecordDetailSearchVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long processId
            ,String code
            ,String workOrderCode
            ,Long workOrderId
            ,String inspectionPeople
            ,String creatorName
            ,String reportOrderCode
            ,String qualityTestingCategoryId
            ,String qcQualityTypeId
            ,String startCreateTime
            ,String endCreateTime
            ,String inspector
            ,String getName
            ,String workshopName
    ){

        Page<QualityTestingRecordDetailSearchVO> pg = new Page<>(page, limit);
        Map paramMap = new HashMap();
        if(processId != null){
            paramMap.put("processId",processId);
        }
        if(StringUtils.isNotBlank(code)){
            paramMap.put("code",code);
        }
        if(StringUtils.isNotBlank(workOrderCode)){
            paramMap.put("workOrderCode",workOrderCode);
        }
        if(StringUtils.isNotBlank(inspectionPeople)){
            paramMap.put("inspectionPeople",inspectionPeople);
        }
        if(StringUtils.isNotBlank(creatorName)){
            paramMap.put("creatorName",creatorName);
        }
        paramMap.put("workOrderId",workOrderId);
        if(StringUtils.isNotBlank(reportOrderCode)){
            paramMap.put("reportOrderCode",reportOrderCode);
        }
        if(StringUtils.isNotBlank(qualityTestingCategoryId)){
            paramMap.put("qualityTestingCategoryId",qualityTestingCategoryId);
        }
        if(StringUtils.isNotBlank(qcQualityTypeId)){
            paramMap.put("qcQualityTypeId",qcQualityTypeId);
        }
        if(StringUtils.isNotBlank(startCreateTime)){
            paramMap.put("startCreateTime",startCreateTime);
        }
        if(StringUtils.isNotBlank(endCreateTime)){
            paramMap.put("endCreateTime",endCreateTime);
        }
        if(StringUtils.isNotBlank(inspector)){
            paramMap.put("inspector",inspector);
        }
        if(StringUtils.isNotBlank(getName)){
            paramMap.put("getName",getName);
        }
        if(StringUtils.isNotBlank(workshopName)){
            paramMap.put("workshopName",workshopName);
        }
        IPage<QualityTestingRecordDetailSearchVO> list = qualityTestingRecordService.pageList4appNew(pg,paramMap);
        list.getRecords().forEach(info->{
            //设置状态
            info.setStatusName(ProductEnum.qualityStatusEmum.getNameByCode(info.getStatus()));
            //设置结果
            if(null!=info.getQualityTestingResult()) {
                if (info.getQualityTestingResult().equals(ProductEnum.qualityResultNameEmum.HG.getCode())) {
                    info.setQualityTestingResultName(QualityTestingRecordDetail.QualityTestingResult.qualified.getDesc());
                } else if (info.getQualityTestingResult().equals(ProductEnum.qualityResultNameEmum.BHG.getCode())) {
                    info.setQualityTestingResultName(QualityTestingRecordDetail.QualityTestingResult.unqualified.getDesc());
                }
            }else {
                info.setQualityTestingResultName(QualityTestingRecordDetail.QualityTestingResult.other.getDesc());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加质检记录表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addQualityDetail")
    @Idempotent(keyPrefix = "taskQualityRecordAdd")
    public JsonResult addQualityDetail(@RequestBody QualityRecordAddOrUpdateForm qualityTestingRecordForm) {
        if (qualityTestingRecordService.addQualityDetail(qualityTestingRecordForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }
    @ApiOperation(value = "提交质检记录", notes = "添加")
    @PostMapping("/submitTestingRecord")
    @Idempotent(keyPrefix = "taskQualityRecordSubmit")
    public JsonResult submitTestingRecord(@RequestBody QualityTestingRecordForm qualityTestingRecordForm) {
        try {
            qualityTestingRecordService.submitTestingRecord(qualityTestingRecordForm);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("提交质检记录接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }

    @ApiOperation(value = "修改质检记录表", notes = "修改")
    @PutMapping("/updateQualityDetail")
    @Idempotent(keyPrefix = "taskQualityRecordUpdate")
    public JsonResult updateQualityDetail(@RequestBody QualityRecordAddOrUpdateForm qualityTestingRecordForm) {
        QualityTestingRecord qualityTestingRecord = qualityTestingRecordService.getById(qualityTestingRecordForm.getId());
        if(qualityTestingRecord == null){
            return JsonResult.fail("修改失败！");
        }
        if(qualityTestingRecordService.updateQualityDetail(qualityTestingRecordForm)>0){
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "修改质检记录表", notes = "修改")
    @PutMapping("/update")
    @Idempotent(keyPrefix = "taskQualityRecordUpSubmit")
    public JsonResult update(@Validated(QualityTestingRecordForm.Update.class) QualityTestingRecordForm qualityTestingRecordForm) {
        QualityTestingRecord qualityTestingRecord = qualityTestingRecordService.getById(qualityTestingRecordForm.getId());
        if(qualityTestingRecord == null){
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(QualityTestingRecord.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(qualityTestingRecordForm, qualityTestingRecord, copyOptions);
        if (qualityTestingRecordService.updateById(qualityTestingRecord)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "提交质检结果信息", notes = "提交-质检结果")
    @PostMapping("/submitResultValue")
    @Idempotent(keyPrefix = "taskQualityRecordSubmitValue")
    public JsonResult submitResultValue(@RequestBody QualityDetailRecordSimpleVo simpleVo) {

        QualityTestingRecordDetail detailServiceById = qualityTestingRecordDetailService.getById(simpleVo.getRecordId());
        if(detailServiceById == null){
            return JsonResult.fail("提交失败！");
        }
        if(qualityTestingRecordService.submitResultValue(simpleVo)>0){
            return JsonResult.success("提交成功！");
        }
        return JsonResult.fail("提交失败！");
    }

    /**
     * 根据质检记录详情 查询质检参数信息
     * @param recordDetailId
     * @param taskId
     * @return
     */
    @ApiOperation(value = "根据质检记录详情", notes = "查询-质检参数信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "recordDetailId", value = "质检任务详情id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "taskId", value = "质检任务id", required = true, dataType = "Long")
    })
    @GetMapping("/getDetailRecordValue" )
    public JsonResult<QualityDetailRecordInfoVo> getDetailRecordValue(Long taskId, Long recordDetailId,Long bookId) {
        QualityDetailRecordInfoVo resultsData = qualityTestingRecordService.getDetailRecordValue(taskId,recordDetailId,bookId);
        return JsonResult.success(resultsData);
    }

    @ApiOperation(value = "任务记录下的样品配置", notes = "查询-样品配置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "质检任务id", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/getRecordResultsData" )
    public JsonResult<List<QualityRecordDetailInfoVo>> getRecordResultsData(Long recordId,Long processId) {
        List<QualityRecordDetailInfoVo> resultsData = qualityTestingRecordService.getRecordResultsData(recordId,processId);
        resultsData.forEach(info->{
            info.setStatusName(ProductEnum.qualityStatusEmum.getNameByCode(info.getStatus()));
        });
        return JsonResult.success(resultsData);
    }



    @ApiOperation(value = "获取不合格错误信息", notes = "查询-不合格错误信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "processId", value = "开工单种的工序id", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/getAbnormalCauseBy/{processId}" )
    public JsonResult<List<ProAbnormalCause>> getAbnormalCauseBy(@PathVariable("processId") Long processId) {
        List<ProAbnormalCause> causes = qualityTestingRecordService.getAbnormalCauseBy(processId);
        if (CollectionUtils.isEmpty(causes)) {
            causes = new ArrayList<>();
        }
        return JsonResult.success(causes);
    }



}
